<template>
  <div class="region-add">
    <nav-back />
    <div class="search-bar">
      <i class="search-icon" :style="{backgroundImage:`url('${searchIco}')`}"></i>
      <input
        type="text"
        class="input-search"
        v-model="keywords"
        placeholder="请输入城市名称"
        maxlength="10"
        @input="handleSearch"
      />
    </div>
    <div class="city-list">
      <p
        v-for="v in cityList"
        :key="v.adcode"
        class="city-item"
        @click="handleClick(v)"
      >{{v.name}}</p>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import { NavBack } from '@/components'
import searchIco from '@/assets/icons/search.png'

export default {
  name: 'region-add',
  components: { NavBack },
  computed: { ...mapState('Region', ['cityList']) },
  data: () => ({
    searchIco,
    keywords: '',
    timer: null // 用于函数防抖
  }),
  methods: {
    ...mapActions('Region', ['searchRegion', 'addCity']),
    ...mapMutations('Region', ['clearCityList']),
    handleSearch() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.searchRegion(this.keywords)
      }, 1000)
    },
    handleClick(city) {
      this.addCity(city)
      this.$router.replace({ name: 'region-select' })
    }
  },
  beforeRouteLeave(from, to, next) {
    this.keywords = ''
    this.clearCityList()
    next()
  }
}
</script>

<style lang="stylus" scoped>
$input-size = 20px;

.region-add {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;

  .search-bar {
    position: relative;
    width: 80%;
    margin: 10px auto;
  }

  .search-icon {
    position: absolute;
    top: 50%;
    left: 0.75 * $input-size;
    width: 0.8 * $input-size;
    height: 0.8 * $input-size;
    background: center / cover no-repeat;
    transform: translateY(-50%);
  }

  .input-search {
    display: block;
    width: 100%;
    padding: 0.25 * $input-size 0.75 * $input-size;
    line-height: $input-size;
    font-size: 16px;
    text-indent: 2em;
    border: none;
    outline: none;
    border-radius: $input-size;
    background-color: $app-bgc;
    box-sizing: border-box;
    color: $font-color;
  }

  .city-list {
    flex: 1;
    overflow: scroll;
  }

  .city-item {
    margin: 20px 16px;
    padding-bottom: 20px;
    color: $font-gray;
    border-bottom: 1px solid $border-color;
  }
}
</style>
